package com.yanghx.springtarnjms.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.connection.JmsTransactionManager;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.transaction.PlatformTransactionManager;

import javax.jms.ConnectionFactory;

/**
 * @author yangHX
 * createTime  2019/8/8 21:44
 */
@EnableJms
@Configuration
@Slf4j
public class JmsConfig {


    @Bean
    public JmsTemplate initJmsTemplate(ConnectionFactory connectionFactory) {
        log.debug("init jms template with converter ");
        JmsTemplate template = new JmsTemplate();
        //jmsTemplate 使用的connectionFactory 跟JmsTransactionManage使用的必须是同一个，不能在这里封装成caching之类的
        template.setConnectionFactory(connectionFactory);
        return template;
    }

    /**
     * 这个用于设置@JmsListener使用的connectionFactoy
     *
     * @param connectionFactory  连接工厂
     * @param configurer         配置信息
     * @param transactionManager 事务管理器
     * @return transactionManager
     */
    @Bean
    public JmsListenerContainerFactory<?> msgFactory(ConnectionFactory connectionFactory
            , DefaultJmsListenerContainerFactoryConfigurer configurer
            , PlatformTransactionManager transactionManager) {

        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setTransactionManager(transactionManager);
        factory.setCacheLevelName("CACHE_CONNECTION");
        //10秒
        factory.setReceiveTimeout(10000L);
        configurer.configure(factory, connectionFactory);
        return factory;
    }

    @Bean
    public PlatformTransactionManager transactionManager(ConnectionFactory connectionFactory) {
        return new JmsTransactionManager(connectionFactory);
    }
}
